package com.lyf.auth.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimeUtil {
   private static final Logger logger = LoggerFactory.getLogger(TimeUtil.class);

   public static Date getDate() {
      return Calendar.getInstance().getTime();
   }

   public static long getNowTimeMs() {
      return System.currentTimeMillis();
   }

   public static long getNowTimeSeconds() {
      return getNowTimeMs() / 1000L;
   }

   public static boolean checkTimeValid(Long timestamp1, Long validPeriod) {
      logger.info("timestamp:{}, validPeriod:{}", timestamp1, validPeriod);
      Long timestamp2 = getNowTimeMs();
      if (timestamp1 != null && validPeriod != null) {
         long value = timestamp2 - timestamp1;
         return value > 0L && value < 1000L * validPeriod;
      } else {
         return false;
      }
   }

   public static Long dateToStamp(String str) throws Exception {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date = simpleDateFormat.parse(str);
      long ts = date.getTime();
      return ts;
   }

   public static String stamp2Date(Long stamp) throws Exception {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String dateStr = simpleDateFormat.format(stamp);
      return dateStr;
   }

   public static String stamp2Date2(Long stamp) throws Exception {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      String dateStr = simpleDateFormat.format(stamp);
      return dateStr;
   }

   public static String time2Str(Long timestamp, String dateFormat) {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
      return simpleDateFormat.format(timestamp);
   }

   public static Long str2Time(String str, String dateFormat) throws Exception {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
      Date date = simpleDateFormat.parse(str);
      return date.getTime();
   }
}
